package com.ruoyi.business.service;

import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.business.WechartSend;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;


/**
 * @author ：jiangguanjun
 * @description：网站浏览记录
 * @date ：2020/7/16 21:13
 */
@Slf4j
@Component
public class PushMessageService {

    @Autowired
    private RestTemplate restTemplate ;


    @Value("${weixin.app_id}")
    private String appId ;

    @Value("${weixin.secret}")
    private String secret ;

    @Value("${weixin.url}")
    private String url ;
    @Value("${weixin.messagePath}")
    private String messagePath ;

    @Autowired
    private WechartService wechartService ;



    public Boolean send(JSONObject jsonObject, String templateId, String openId, String skipUrl){

        WechartSend wechartSend = new WechartSend() ;
        wechartSend.setTouser(openId);
        wechartSend.setTemplate_id(templateId);
        wechartSend.setUrl(skipUrl);
        wechartSend.setData(jsonObject);
        String accessToken = wechartService.getAccessToken() ;
        String urlReq = url+messagePath+"?access_token="+ accessToken;

        log.info("urlReq::::::{}",urlReq);

        String req = JSONObject.toJSONString(wechartSend) ;
        log.info("req::::::::{}",req);
        HttpHeaders httpHeaders = new HttpHeaders() ;
        httpHeaders.setContentType(MediaType.APPLICATION_JSON);

        HttpEntity httpEntity = new HttpEntity(req,httpHeaders) ;

        String res = restTemplate.postForObject(urlReq,httpEntity,String.class) ;

        log.info("res::::{}",res);
        JSONObject resJSON = JSONObject.parseObject(res) ;
        if(resJSON.getInteger("errcode") != 0){
            log.info("推送微信消息失败msgid：{}",resJSON.getLong("msgid"));
            return true ;
        }else{
            return true ;
        }

    }



}
